package com.ecloud.gardensterminal.server.mqtt;

import com.ecloud.gardensterminal.constant.MqttTopic;
import com.ecloud.gardensterminal.mqtt.MqttMessageFactory;
import com.ecloud.gardensterminal.mqtt.constant.MqttInitializer;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author Squbi
 */
@Component
public class MqttInitImpl implements MqttInitializer {
    private static final Logger LOGGER = LoggerFactory.getLogger(MqttInitImpl.class);
    private final MqttMessageFactory messageFactory = new MqttMessageFactory();

    @Override
    public void init(MqttClient client) throws MqttException {
        client.subscribe(MqttTopic.TERMINAL_TOPIC, 2);
        LOGGER.info("subscribe topic `{}`", MqttTopic.TERMINAL_TOPIC);
        MqttMessage message = messageFactory.createMessage(MqttTopic.TERMINAL_TOPIC.getBytes());
        client.publish(MqttTopic.SERVER_TOPIC, message);
        LOGGER.info("publish topic `{}` message `{}`", MqttTopic.SERVER_TOPIC, MqttTopic.TERMINAL_TOPIC);
    }
}
